package com.ysd.lis.service.bac.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.bac.*;
import com.ysd.lis.entity.lab.LabCriticalReport;
import com.ysd.lis.entity.lab.LabMaininfo;
import com.ysd.lis.mapper.bac.*;
import com.ysd.lis.mapper.lab.LabMaininfoMapper;
import com.ysd.lis.request.bac.BacObserStrainAlarmEntry;
import com.ysd.lis.service.bac.BacObserResultService;
import com.ysd.util.ToolsUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 菌落观察结果 服务实现类
 * </p>
 *
 * @author cfz
 * @since 2024-03-27
 */
@Service
public class BacObserResultServiceImpl extends ServiceImpl<BacObserResultMapper, BacObserResult> implements BacObserResultService {
    @Autowired
    BacObserResultMapper bacObserResultMapper;
    @Autowired
    BacStrainLogMapper bacStrainLogMapper;
    @Autowired
    BacMorphologyLogMapper bacMorphologyLogMapper;
    @Autowired
    BacStainingResultMapper bacStainingResultMapper;
    @Autowired
    LabMaininfoMapper labMaininfoMapper;

    @Override
    public Result findBacObserResultList(BacObserResult bacObserResult) {
        List<BacObserResult> list = findBacObserResultArray(bacObserResult);
        return Result.succ(1, "请求成功", list);
    }

    @Override
    public List<BacObserResult> findBacObserResultArray(BacObserResult bacObserResult) {
        if (StringUtils.isBlank(bacObserResult.getRptGroup())) {
            throw new RuntimeException("报告单元为空");
        }
        if (StringUtils.isBlank(bacObserResult.getSampleNo())) {
            throw new RuntimeException("标本号");
        }
        if (BeanUtil.isEmpty(bacObserResult.getSampleda())) {
            throw new RuntimeException("检验日期为空");
        }
        MPJLambdaWrapper<BacObserResult> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(BacObserResult::getDelFlag, 0);
        //queryWrapper.eq(StringUtils.isNotBlank(bacObserResult.getMaininfoId()), BacObserResult::getMaininfoId, bacObserResult.getMaininfoId());

        queryWrapper.eq(BacObserResult::getRptGroup, bacObserResult.getRptGroup());
        queryWrapper.eq(BacObserResult::getSampleNo, bacObserResult.getSampleNo());
        Timestamp timestamp = new Timestamp(bacObserResult.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
        queryWrapper.ge(BacObserResult::getSampleda, startTime);
        queryWrapper.le(BacObserResult::getSampleda, endTime);
        queryWrapper.eq(StringUtils.isNotBlank(bacObserResult.getTestFlowNo()), BacObserResult::getTestFlowNo, bacObserResult.getTestFlowNo());
        queryWrapper.eq(StringUtils.isNotBlank(bacObserResult.getTestNodeNo()), BacObserResult::getTestNodeNo, bacObserResult.getTestNodeNo());
        queryWrapper.eq(StringUtils.isNotBlank(bacObserResult.getIsolateNum()), BacObserResult::getIsolateNum, bacObserResult.getIsolateNum());
        queryWrapper.eq(Objects.nonNull(bacObserResult.getBacPublishStatus()), BacObserResult::getBacPublishStatus, bacObserResult.getBacPublishStatus());
        return bacObserResultMapper.selectList(queryWrapper);
    }

    @Override
    public Result addBacObserResult(BacObserResult bacObserResult) {
        int i = bacObserResultMapper.insert(bacObserResult);
        if (i > 0) {
            return Result.succ(1, "新增成功", bacObserResult);
        }
        return Result.fail("新增失败");
    }

    @Override
    public Result deleteBacObserResult(BacObserResult bacObserResult) {
        bacObserResult.setDelFlag(1);
        int i = bacObserResultMapper.updateById(bacObserResult);
        if (i > 0) {
            return Result.succ(1, "删除成功", bacObserResult);
        }
        return Result.fail("删除失败");
    }

    @Override
    public Result updateBacObserResult(BacObserResult bacObserResult) {
        int i = bacObserResultMapper.updateById(bacObserResult);
        if (i > 0) {
            return Result.succ(1, "更新成功", bacObserResult);
        }
        return Result.fail("更新失败");
    }

    @Autowired
    BacBloodCultrueMapper bacBloodCultrueMapper;
    @Autowired
    BacTestResultMapper bacTestResultMapper;
    @Override
    public Result saveOrUpdateBacObserResult(BacObserResult bacObserResult) {
        if (StringUtils.isNotBlank(bacObserResult.getId())) {
            bacObserResultMapper.updateById(bacObserResult);
        } else {
            bacObserResultMapper.insert(bacObserResult);
        }

        if (StringUtils.isNotBlank(bacObserResult.getCultureMedium()) && StringUtils.isNotBlank(bacObserResult.getMorphology())) {
            BacStrainLog bacStrainLog = new BacStrainLog();
            BeanUtils.copyProperties(bacObserResult, bacStrainLog);
            bacStrainLog.setId(null);

            //bacStrainLog.setStrainId(bacObserResult.getIsolateNum());
            bacStrainLog.setStrainNo(bacObserResult.getIsolateNum());
            bacStrainLog.setRptGroup(bacObserResult.getRptGroup());
            bacStrainLog.setSampleda(bacObserResult.getSampleda());
            bacStrainLog.setSampleNo(bacObserResult.getSampleNo());
            bacStrainLog.setTestFlowNo(bacObserResult.getTestFlowNo());
            bacStrainLog.setTestNodeNo(bacObserResult.getTestNodeNo());

            bacStrainLog.setContent("编辑形态:" + bacObserResult.getCultureMedium() + "(" + bacObserResult.getMorphology() + ")");
            bacStrainLogMapper.insert(bacStrainLog);

            BacMorphologyLog bacMorphologyLog = new BacMorphologyLog();
            //bacMorphologyLog.setObserResultId(bacObserResult.getId());

            bacMorphologyLog.setRptGroup(bacObserResult.getRptGroup());
            bacMorphologyLog.setSampleda(bacObserResult.getSampleda());
            bacMorphologyLog.setSampleNo(bacObserResult.getSampleNo());
            bacMorphologyLog.setTestFlowNo(bacObserResult.getTestFlowNo());
            bacMorphologyLog.setTestNodeNo(bacObserResult.getTestNodeNo());
            bacMorphologyLog.setIsolateNum(bacObserResult.getIsolateNum());

            bacMorphologyLog.setCultureMedium(bacObserResult.getCultureMedium());
            bacMorphologyLog.setMorphology(bacObserResult.getMorphology());
            bacMorphologyLogMapper.insert(bacMorphologyLog);
        }

        String rptGroup = bacObserResult.getRptGroup();
        String sampleNo = bacObserResult.getSampleNo();
        Timestamp sampleda = bacObserResult.getSampleda();

        Timestamp timestamp = new Timestamp(sampleda.getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
        Integer isAlarmCnt = 0;
        //查询培养观察结果中是否有危急值数据
        MPJLambdaWrapper<BacObserResult> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(BacObserResult::getDelFlag, 0)
                .eq(BacObserResult::getRptGroup, rptGroup)
                .eq(BacObserResult::getSampleNo, sampleNo)
                .ge(BacObserResult::getSampleda, startTime)
                .le(BacObserResult::getSampleda, endTime)
                .eq(BacObserResult::getIsAlarm, 1);
        Integer obsCnt = bacObserResultMapper.selectCount(queryWrapper);
        isAlarmCnt += obsCnt;

        //查询血培养结果中是否有危急值数据
        MPJLambdaWrapper<BacBloodCultrue> queryWrapperb = new MPJLambdaWrapper<>();
        queryWrapperb.eq(BacBloodCultrue::getDelFlag, 0)
                .eq(BacBloodCultrue::getRptGroup, rptGroup)
                .eq(BacBloodCultrue::getSampleNo, sampleNo)
                .ge(BacBloodCultrue::getSampleda, startTime)
                .le(BacBloodCultrue::getSampleda, endTime)
                .eq(BacBloodCultrue::getIsAlarm, 1);
        Integer culCnt = bacBloodCultrueMapper.selectCount(queryWrapperb);
        isAlarmCnt += culCnt;

        //查询细菌结果中是否有危急值数据
        MPJLambdaWrapper<BacTestResult> queryWrapperR = new MPJLambdaWrapper<>();
        queryWrapperR.eq(BacTestResult::getDelFlag, 0)
                .eq(BacTestResult::getRptGroup, rptGroup)
                .eq(BacTestResult::getSampleNo, sampleNo)
                .ge(BacTestResult::getSampleda, startTime)
                .le(BacTestResult::getSampleda, endTime)
                .eq(BacTestResult::getIsAlarm, 1);
        Integer rptCnt = bacTestResultMapper.selectCount(queryWrapperR);
        isAlarmCnt += rptCnt;

        LambdaUpdateWrapper<LabMaininfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(LabMaininfo::getRptGroup, rptGroup)
                .eq(LabMaininfo::getSampleda, sampleda)
                .eq(LabMaininfo::getSampleNo,sampleNo);
        if (isAlarmCnt > 0) {
            lambdaUpdateWrapper.set(LabMaininfo::getIsAlarm, 1);
        }else{
            lambdaUpdateWrapper.set(LabMaininfo::getIsAlarm, 0);
        }
        labMaininfoMapper.update(null, lambdaUpdateWrapper);


        return Result.succ(1, "保存成功", bacObserResult);
    }

    @Override
    public Result getAlarmResult(BacObserResult bacObserResult) {
        Timestamp timestamp = new Timestamp(bacObserResult.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");

        MPJLambdaWrapper<BacObserResult> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(BacObserResult.class);
        lambdaQueryWrapper.leftJoin(LabCriticalReport.class, LabCriticalReport::getResultId, BacObserResult::getId);
        lambdaQueryWrapper.and(wrapper -> wrapper
                .eq(BacObserResult::getRptGroup, bacObserResult.getRptGroup())//防止格式化
                .eq(BacObserResult::getSampleNo, bacObserResult.getSampleNo())//防止格式化
                .ge(BacObserResult::getSampleda, startTime)//防止格式化
                .le(BacObserResult::getSampleda, endTime));//防止格式化
        lambdaQueryWrapper.eq(BacObserResult::getIsAlarm, 1);
        lambdaQueryWrapper.eq(BacObserResult::getDelFlag, 0);
        lambdaQueryWrapper.isNull(LabCriticalReport::getResultId);
        lambdaQueryWrapper.eq(ToolsUtils.isNotEmpty(bacObserResult.getTestFlowNo()), BacObserResult::getTestFlowNo, bacObserResult.getTestFlowNo());
        lambdaQueryWrapper.eq(ToolsUtils.isNotEmpty(bacObserResult.getTestNodeNo()), BacObserResult::getTestNodeNo, bacObserResult.getTestNodeNo());
        List<BacObserResult> labRptresults = this.baseMapper.selectList(lambdaQueryWrapper);

        List<BacObserStrainAlarmEntry> resList = new ArrayList<>();

        /*培养观察危急值*/
        for (BacObserResult m : labRptresults) {
            BacObserStrainAlarmEntry entry = new BacObserStrainAlarmEntry();
            entry.setIsReport("0");
            entry.setIsolateNum(m.getIsolateNum());
            entry.setMorphologyName(m.getMorphologyName());
            entry.setExperiment(m.getExperiment());
            entry.setBacRate(m.getBacRate());
            entry.setStrainCount(m.getStrainCount());
            entry.setAlarmText(m.getAlarmText());
            entry.setAlarmType("1");
            entry.setId(m.getId());
            entry.setRptGroup(m.getRptGroup());
            entry.setSampleda(m.getSampleda());
            entry.setSampleNo(m.getSampleNo());
            resList.add(entry);
        }
        /*染色图片危急值*/
        MPJLambdaWrapper<BacStainingResult> lambdaQueryStainingWrapper = new MPJLambdaWrapper<>();
        lambdaQueryStainingWrapper.selectAll(BacStainingResult.class);
        lambdaQueryStainingWrapper.leftJoin(LabCriticalReport.class, LabCriticalReport::getResultId, BacStainingResult::getId);
        lambdaQueryStainingWrapper.and(wrapper -> wrapper
                .eq(BacStainingResult::getRptGroup, bacObserResult.getRptGroup())//防止格式化
                .eq(BacStainingResult::getSampleNo, bacObserResult.getSampleNo())//防止格式化
                .ge(BacStainingResult::getSampleda, startTime)//防止格式化
                .le(BacStainingResult::getSampleda, endTime));//防止格式化
        lambdaQueryStainingWrapper.eq(BacStainingResult::getIsAlarm, 1);
        lambdaQueryStainingWrapper.eq(BacStainingResult::getDelFlag, 0);
        lambdaQueryStainingWrapper.isNull(LabCriticalReport::getResultId);
        lambdaQueryStainingWrapper.eq(ToolsUtils.isNotEmpty(bacObserResult.getTestFlowNo()), BacStainingResult::getTestFlowNo, bacObserResult.getTestFlowNo());
        lambdaQueryStainingWrapper.eq(ToolsUtils.isNotEmpty(bacObserResult.getTestNodeNo()), BacStainingResult::getTestNodeNo, bacObserResult.getTestNodeNo());
        List<BacStainingResult> bacStainingResultList = bacStainingResultMapper.selectList(lambdaQueryStainingWrapper);

        for (BacStainingResult m : bacStainingResultList) {
            BacObserStrainAlarmEntry entry = new BacObserStrainAlarmEntry();
            entry.setIsReport("0");
            entry.setIsolateNum(m.getStrainNo());
            entry.setMorphologyName("");
            entry.setExperiment("");
            entry.setBacRate(null);
            entry.setStrainCount("");
            entry.setAlarmText(m.getDescText() + (ToolsUtils.isNotEmpty(m.getStainingConcOptNa()) ? m.getStainingConcOptNa() : ""));
            entry.setAlarmType("2");
            entry.setId(m.getId());
            entry.setRptGroup(m.getRptGroup());
            entry.setSampleda(m.getSampleda());
            entry.setSampleNo(m.getSampleNo());
            resList.add(entry);
        }

        return Result.succ(1, "成功", resList);
    }
}
